package com.plpm.controller;

import com.plpm.model.FileInfo;
import com.plpm.service.FileUploadService;
import com.plpm.service.IoTDBService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 文件管理控制器
 *
 * @author PLPM Team
 * @version 1.0
 */
@Slf4j
@Controller
@RequestMapping("/files")
public class FileController {

    @Autowired
    private FileUploadService fileUploadService;

    @Autowired
    private IoTDBService iotdbService;

    /**
     * 文件管理页面 - 返回Vue SPA应用
     */
    @GetMapping("/page")
    public String fileManagementPage() {
        // 直接返回静态HTML页面，Vue应用会通过API获取数据
        return "forward:/index.html";
    }

    /**
     * 开始文件上传
     */
    @PostMapping("/upload/start")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> startUpload(
            @RequestParam("fileName") String fileName,
            @RequestParam("fileSize") long fileSize,
            @RequestParam("fileType") String fileType) {

        Map<String, Object> response = new HashMap<>();

        try {
            String fileId = fileUploadService.startFileUpload(fileName, fileSize, fileType);
            response.put("success", true);
            response.put("fileId", fileId);
            response.put("message", "文件上传已开始");

            log.info("File upload started: fileId={}, fileName={}", fileId, fileName);

        } catch (Exception e) {
            log.error("Failed to start file upload: fileName={}", fileName, e);
            response.put("success", false);
            response.put("message", "开始文件上传失败: " + e.getMessage());
        }

        return ResponseEntity.ok(response);
    }

    /**
     * 上传文件分片
     */
    @PostMapping("/upload/chunk")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> uploadChunk(
            @RequestParam("fileId") String fileId,
            @RequestParam("chunkIndex") int chunkIndex,
            @RequestParam("chunk") MultipartFile chunkFile) {

        Map<String, Object> response = new HashMap<>();

        try {
            boolean success = fileUploadService.uploadChunk(fileId, chunkIndex, chunkFile);

            if (success) {
                response.put("success", true);
                response.put("message", "分片上传成功");
            } else {
                response.put("success", false);
                response.put("message", "分片上传失败");
            }

        } catch (Exception e) {
            log.error("Failed to upload chunk: fileId={}, chunkIndex={}", fileId, chunkIndex, e);
            response.put("success", false);
            response.put("message", "分片上传失败: " + e.getMessage());
        }

        return ResponseEntity.ok(response);
    }

    /**
     * 完成文件上传
     */
    @PostMapping("/upload/complete")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> completeUpload(
            @RequestParam("fileId") String fileId,
            @RequestParam(value = "fileSHA256", required = false) String fileSHA256) {
        Map<String, Object> response = new HashMap<>();

        try {
            Map<String, Object> result = fileUploadService.completeFileUpload(fileId, fileSHA256);
            boolean success = (Boolean) result.get("success");

            response.put("success", success);
            response.put("message", result.get("message"));
            
            // 返回SHA256和验证结果
            if (result.containsKey("calculatedSHA256")) {
                response.put("calculatedSHA256", result.get("calculatedSHA256"));
            }
            if (result.containsKey("hashValid")) {
                response.put("hashValid", result.get("hashValid"));
            }

        } catch (Exception e) {
            log.error("Failed to complete file upload: fileId={}", fileId, e);
            response.put("success", false);
            response.put("message", "文件上传完成失败: " + e.getMessage());
        }

        return ResponseEntity.ok(response);
    }

    /**
     * 取消文件上传
     */
    @PostMapping("/upload/cancel")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> cancelUpload(@RequestParam("fileId") String fileId) {
        Map<String, Object> response = new HashMap<>();

        try {
            boolean success = fileUploadService.cancelFileUpload(fileId);

            if (success) {
                response.put("success", true);
                response.put("message", "文件上传已取消");
            } else {
                response.put("success", false);
                response.put("message", "取消文件上传失败");
            }

        } catch (Exception e) {
            log.error("Failed to cancel file upload: fileId={}", fileId, e);
            response.put("success", false);
            response.put("message", "取消文件上传失败: " + e.getMessage());
        }

        return ResponseEntity.ok(response);
    }

    /**
     * 获取上传进度
     */
    @GetMapping("/upload/progress/{fileId}")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> getUploadProgress(@PathVariable String fileId) {
        try {
            Map<String, Object> progress = fileUploadService.getUploadProgress(fileId);
            return ResponseEntity.ok(progress);
        } catch (Exception e) {
            log.error("Failed to get upload progress: fileId={}", fileId, e);
            Map<String, Object> error = new HashMap<>();
            error.put("error", "获取上传进度失败: " + e.getMessage());
            return ResponseEntity.ok(error);
        }
    }

    /**
     * 获取文件列表 - 支持分页
     */
    @GetMapping
    @ResponseBody
    public ResponseEntity<Map<String, Object>> getFileList(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {

        Map<String, Object> response = new HashMap<>();

        try {
            int offset = (page - 1) * size;
            List<FileInfo> fileList = iotdbService.queryFileList(size, offset);
            response.put("success", true);
            response.put("content", fileList);
            response.put("totalElements", fileList.size());
            response.put("totalPages", (int) Math.ceil((double) fileList.size() / size));
            response.put("currentPage", page);
            response.put("size", size);

        } catch (Exception e) {
            log.error("Failed to get file list", e);
            response.put("success", false);
            response.put("message", "获取文件列表失败: " + e.getMessage());
        }

        return ResponseEntity.ok(response);
    }

    /**
     * 获取文件列表 - 兼容旧版本
     */
   /*  @GetMapping("/list")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> getFileListLegacy(
            @RequestParam(defaultValue = "50") int limit,
            @RequestParam(defaultValue = "0") int offset) {

        Map<String, Object> response = new HashMap<>();

        try {
            List<FileInfo> fileList = iotdbService.queryFileList(limit, offset);
            response.put("success", true);
            response.put("data", fileList);
            response.put("total", fileList.size());

        } catch (Exception e) {
            log.error("Failed to get file list", e);
            response.put("success", false);
            response.put("message", "获取文件列表失败: " + e.getMessage());
        }

        return ResponseEntity.ok(response);
    } */

    /**
     * 删除文件
     */
    @DeleteMapping("/{fileName}")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> deleteFile(@PathVariable String fileName) {
        Map<String, Object> response = new HashMap<>();

        try {
            boolean success = iotdbService.deleteFile(fileName);

            if (success) {
                response.put("success", true);
                response.put("message", "文件删除成功");
            } else {
                response.put("success", false);
                response.put("message", "文件删除失败");
            }

        } catch (Exception e) {
            log.error("Failed to delete file: fileName={}", fileName, e);
            response.put("success", false);
            response.put("message", "文件删除失败: " + e.getMessage());
        }

        return ResponseEntity.ok(response);
    }

    /**
     * 保存文件信息
     */
    @PostMapping("/save")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> saveFileInfo(@RequestBody Map<String, Object> fileData) {
        Map<String, Object> response = new HashMap<>();

        try {
            // TODO: 实现文件信息保存逻辑
            log.info("Saving file info: {}", fileData);
            response.put("success", true);
            response.put("message", "文件信息保存成功");

        } catch (Exception e) {
            log.error("Failed to save file info", e);
            response.put("success", false);
            response.put("message", "保存文件信息失败: " + e.getMessage());
        }

        return ResponseEntity.ok(response);
    }

    /**
     * 文件上传 - 简单版本
     */
    @PostMapping("/upload")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> uploadFiles(@RequestParam("files") MultipartFile[] files) {
        Map<String, Object> response = new HashMap<>();

        try {
            log.info("Uploading {} files", files.length);

            // 验证文件
            if (files == null || files.length == 0) {
                response.put("success", false);
                response.put("message", "没有选择任何文件");
                return ResponseEntity.badRequest().body(response);
            }

            // 验证文件
            for (MultipartFile file : files) {
                if (file.isEmpty()) {
                    response.put("success", false);
                    response.put("message", "文件不能为空: " + file.getOriginalFilename());
                    return ResponseEntity.badRequest().body(response);
                }

                String fileName = file.getOriginalFilename();
                if (StringUtils.isEmpty(fileName) || fileName.trim().isEmpty()) {
                    response.put("success", false);
                    response.put("message", "文件名不能为空");
                    return ResponseEntity.badRequest().body(response);
                }
            }

            // 保存文件
            List<String> savedFiles = new ArrayList<>();
            for (MultipartFile file : files) {
                try {
                    String fileName = file.getOriginalFilename();
                    String filePath = fileUploadService.saveFile(file);
                    savedFiles.add(fileName);
                    log.info("File saved successfully: {} -> {}", fileName, filePath);
                } catch (Exception e) {
                    log.error("Failed to save file: {}", file.getOriginalFilename(), e);
                    response.put("success", false);
                    response.put("message", "保存文件失败: " + file.getOriginalFilename() + " - " + e.getMessage());
                    return ResponseEntity.ok(response);
                }
            }

            response.put("success", true);
            response.put("message", "文件上传成功");
            response.put("uploadedCount", files.length);
            response.put("savedFiles", savedFiles);

        } catch (Exception e) {
            log.error("Failed to upload files", e);
            response.put("success", false);
            response.put("message", "文件上传失败: " + e.getMessage());
        }

        return ResponseEntity.ok(response);
    }
}
